﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace ClusteringWrraper
{
    public class QueryHelper
    {
        public delegate void AsyncResultHandler(object data, string res);

        public static void GetResAsync(string str, string token, object data, AsyncResultHandler foo)
        {
            var friendsUrl = @"https://api.facebook.com/method/" + str + "access_token=" + token + "&format=json";
            var request = WebRequest.Create(friendsUrl) as HttpWebRequest;
            var state = new RequestState(request, data, friendsUrl, foo);
            if (request != null)
                request.BeginGetResponse(Callback, state);
        }

        private static void Callback(IAsyncResult result)
        {
            var state = (RequestState)(result.AsyncState);
            var data = state.Data;
            var request = state.Request;
            request.Timeout = 15000;
            // get the Response
            var response =
            (HttpWebResponse)request.EndGetResponse(result);
            var s = response.GetResponseStream();
            var readStream = new StreamReader(s);
            var dataString = readStream.ReadToEnd();
            response.Close();
            s.Close();
            readStream.Close();
            if (state.ResultHandler != null)
            {
                ((AsyncResultHandler) state.ResultHandler)(data, dataString);
            }
        }

        public static string GetRes(string str, string token)
        {
            string friendsUrl = @"https://api.facebook.com/method/" + str + "access_token=" + token + "&format=json";
            var request = WebRequest.Create(friendsUrl) as HttpWebRequest;
            var res = "";

            try
            {
                if (request != null)
                {
                    request.Timeout = 15000;
                    using (var response
                        = request.GetResponse() as HttpWebResponse)
                    {
                        if (response != null)
                        {
                            var reader
                                = new StreamReader(response.GetResponseStream());

                            res = reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                throw new Exception(ex.Message);
            }
            return res;
        }

        public static string HttpPost(string token, string uri, LinkedList<KeyValuePair<String,String>> parameters)
        {
            // create a request
            var postData = string.Format("?access_token={0}",token);

            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    postData = String.Format("{0}&{1}={2}", postData, parameter.Key, parameter.Value);
                }
            }

            var request = (HttpWebRequest)
            WebRequest.Create(uri); request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";
 
            // turn our request string into a byte stream
            byte[] postBytes = Encoding.ASCII.GetBytes(postData);
 
            // this is important - make sure you specify type this way
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postBytes.Length;
            Stream requestStream = request.GetRequestStream();
 
            // now send it
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();
 
            // grab te response and print it out to the console along with the status code
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
            Console.WriteLine(response.StatusCode);

            return (new StreamReader(response.GetResponseStream()).ReadToEnd() + Environment.NewLine + response.StatusCode);
        }
    }
}
